<template>
    <div class="about">
      <div>
        <p>
          <span>{{ location.name }}</span>
          实时天气
        </p>
        <p>数据观测时间：{{ timeFormat }}</p>
      </div>
      <div>
        <p><i :class="iconName"></i></p>
        <p>温度：{{ now.temp }}</p>
        <p>体感温度：{{ now.feelsLike }}</p>
      </div>
      <div>
        <p>天气预警：无{{now.warning}}</p>
      </div>
      <div>
      <p>空气质量指数：良{{ airQuality.aqi }}</p>
      <p>空气质量等级：三级{{ airQuality.quality }}</p>
    </div>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  import { API_NOW,KEY } from '@/common/constrant';
  import { API_AIR_CURRENT } from '@/common/constrant';
  import { mapState } from 'vuex';
  import dayjs from 'dayjs';
  import "qweather-icons/font/qweather-icons.css"

  export default {
    data() {
      return {
        now:{},
        airQuality: {}
      };
    },
    computed: {
      ...mapState([
        "location"
      ]),
      timeFormat: function (){
        return dayjs(this.now.obsTime).format('YYYY年MM月DD日 HH时mm分')
      },
      iconName: function (){
        return 'qi-'+this.now.icon
      }
    },
    mounted(){
      this.getData();
      this.getAirQualityData();
    },
    methods:{
      getData(){
        axios.get(API_NOW,{
          params:{
            key:KEY,
            location:this.location.id
          }
        }).then(res =>{
          console.log(res.data);
          const { temp, feelsLike, icon, obsTime, warning } = res.data.now;
          this.now = { temp, feelsLike, icon, obsTime, warning };
          //this.now = res.data.now
        })
      },
      getAirQualityData() { // 新增获取空气质量数据的方法
      axios.get(API_AIR_CURRENT, {
        params: {
          key: KEY,
          location: this.location.id
        }
      }).then(res => {
        console.log(res.data);
        const { aqi, quality } = res.data.now; 
        this.airQuality = { aqi, quality };
      }).catch(error => {
        console.error('获取空气质量数据出错：', error);
      });
    }
  },
      //添加监听器
      watch:{
        location:function(){
          this.getData();
          this.getAirQualityData();
        }
      }
    }
  </script>
  
  <style scoped>
  i{
    color:red;
    font-size: 3rem;
  }
  .air-quality-info p {
    margin: 5px 0;
  }
  </style>